package com.chinaedu.oc.util.http;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PropertiesLoaderUtils;

import com.chinaedu.oc.util.common.JsonUtil;
import com.chinaedu.oc.util.common.StringUtil;

/**
 * http接口封装类
 * @Description: TODO
 * @author A18ccms a18ccms_gmail_com 
 * @date 2017年5月9日 下午2:10:43 
 *
 */
public class HttpHelper {
	
	private static String serviceUrl = "";
	
	static {
		Resource resource = new ClassPathResource("/config.properties");
		try {
			Properties props = PropertiesLoaderUtils.loadProperties(resource);
			serviceUrl = props.getProperty("service_url");
			
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 发送http请求,返回的是请求的返回数据，json格式的字符串
	 * @Description: TODO
	 * @param @param iName 接口名称
	 * @param @param param 参数
	 * @param @param clazz 返回值的类型
	 * @param @return
	 * @param @throws HttpRequestException    
	 * @return T    返回类型 
	 * @throws
	 */
	@SuppressWarnings({ "unchecked", "deprecation", "rawtypes" })
	public static String sendRequest(String iName, Object param) throws HttpRequestException {

		iName = serviceUrl + iName;
		
		// 声明HttpClient实例
		HttpClient httpclient = new DefaultHttpClient();
		// 创建HttpPost对象，将要请求的URL通过构造方法传入HttpPost对象。
		HttpPost httpPost = new HttpPost(iName);
		// 建立一个NameValuePair数组，用于存储欲传送的参数
		List nvps = new ArrayList();
		if(param != null) {
			nvps.add(new BasicNameValuePair("data", JsonUtil.toJsonString(param)));
		}
		try {
			httpPost.setEntity(new UrlEncodedFormEntity(nvps, HTTP.UTF_8));// 设置编码
		} catch (UnsupportedEncodingException e1) {
			e1.printStackTrace();
		}
		try {
			// 使用DefaultHttpClient类的execute方法发送HTTP GET或HTTP POST请求，
			HttpResponse response = httpclient.execute(httpPost);
			// 并返回HttpResponse对象。
			HttpEntity entity = response.getEntity();
			StatusLine statusLine = response.getStatusLine();
			// 确认发送
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {// 链接成功
				// 通过HttpResponse接口的getEntity方法返回响应信息，并进行相应的处理。
				String result = EntityUtils.toString(entity);
				
				return result;
			} else {
				// 发送失败时的处理
				throw new HttpRequestException("访问后端接口失败");
			}
		} catch (Exception e) {
			throw new HttpRequestException("访问后端接口失败");
		} finally {
			httpPost.releaseConnection();// 关闭连接
		}
	}
	
	/**
	 * 发送请求并将返回结果根绝clazz转为所需的格式的对象
	 * @Description: TODO
	 * @param @param iName
	 * @param @param param
	 * @param @param clazz
	 * @param @return
	 * @param @throws HttpRequestException    
	 * @return T    返回类型 
	 * @throws
	 */
	public static <T> T sendRequest(String iName, Object param, Class<T> clazz) throws HttpRequestException {
		String result = sendRequest(iName, param);
		return JsonUtil.toBean(result, clazz);
	}
	/**
	 * 发送请求并将返回结果根绝clazz转为所需的格式的List
	 * @Description: TODO
	 * @param @param iName
	 * @param @param param
	 * @param @param clazz
	 * @param @return
	 * @param @throws HttpRequestException    
	 * @return List<T>    返回类型 
	 * @throws
	 */
	public static <T> List<T> sendRequestToList(String iName, Object param, Class<T> clazz) throws HttpRequestException{
		String result = sendRequest(iName, param);
		return JsonUtil.toList(result, clazz);
	}
	
	
}
